/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.apps.epocket.quartz;

import com.apps.epocket.manager.MailManager;
import com.apps.epocket.model.MailBean;
import com.apps.epocket.stripes.Configuration;
import com.google.inject.Inject;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;

/**
 *
 * @author Administrator
 */
public class MailProcess implements StatefulJob {

    MailManager mgr;
    Session session;
    
    @Inject Configuration conf;

    @Inject
    public MailProcess(MailManager mgr, Session session) {
        this.mgr = mgr;
        this.session = session;
    }

    public void execute(JobExecutionContext context) throws JobExecutionException {
        List<MailBean> allMail = mgr.getAllMail();
        for (MailBean mailBean : allMail) {
            System.out.println("About to send mail to -> " + mailBean.getMailTo());
            try {
                //sendMailGoogle(mailBean);
                if (StringUtils.isNotBlank(conf.getProperty("smtp.host")) &&
                        StringUtils.isNotBlank(mailBean.getMailTo()))
                    sendMail(mailBean);
                mgr.delete(mailBean);
            } catch (Exception ex) {
                throw new JobExecutionException(ex);
            }
        }
    }

    public void sendMail(MailBean bean) throws AddressException, MessagingException {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(bean.getMailFrom()));
        if (StringUtils.isNotBlank(bean.getMailTo())) {
            String[] to = bean.getMailTo().split(",");
            InternetAddress[] address = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                address[i] = new InternetAddress();
                address[i].setAddress(to[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        }

        if (StringUtils.isNotBlank(bean.getMailCc())) {
            String[] cc = bean.getMailCc().split(",");
            InternetAddress[] address = new InternetAddress[cc.length];
            for (int i = 0; i < cc.length; i++) {
                address[i] = new InternetAddress();
                address[i].setAddress(cc[i]);
            }
            msg.setRecipients(Message.RecipientType.CC, address);
        }

        if (StringUtils.isNotBlank(bean.getMailBcc())) {
            String[] bcc = bean.getMailBcc().split(",");
            InternetAddress[] address = new InternetAddress[bcc.length];
            for (int i = 0; i < bcc.length; i++) {
                address[i] = new InternetAddress();
                address[i].setAddress(bcc[i]);
            }
            msg.setRecipients(Message.RecipientType.BCC, address);
        }

        msg.setSubject(bean.getTitle());
        msg.setSentDate(new Date());
        if (StringUtils.isNotBlank(bean.getAttachments())) {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(bean.getContent());
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            String[] files = bean.getAttachments().split(",");
            for (String f : files) {
                File file = new File(f);
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(file);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(file.getName());
                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        } else {
            msg.setDataHandler(new DataHandler(bean.getContent(), "text/plain"));
        }
        Transport.send(msg);
    }

    public void sendMailGoogle(MailBean bean) throws AddressException, MessagingException {
        System.out.println("sending via gmail.com...");
        String host = "smtp.gmail.com";
        String from = "register.pocket@gmail.com";
        String pass = "pocket123";
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true"); // added this line
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
//        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.auth", "true");
        
        
        Authenticator auth = new javax.mail.Authenticator() {

            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                
                return new PasswordAuthentication("register.pocket@gmail.com", "pocket123");
            }
        };
        
        
        Session _session = Session.getDefaultInstance(props, auth);
        
        
        
        Message msg = new MimeMessage(_session);
        msg.setFrom(new InternetAddress(from));
        if (StringUtils.isNotBlank(bean.getMailTo())) {
            String[] to = bean.getMailTo().split(",");
            InternetAddress[] address = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                address[i] = new InternetAddress();
                address[i].setAddress(to[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        }

        if (StringUtils.isNotBlank(bean.getMailCc())) {
            String[] cc = bean.getMailCc().split(",");
            InternetAddress[] address = new InternetAddress[cc.length];
            for (int i = 0; i < cc.length; i++) {
                address[i] = new InternetAddress();
                address[i].setAddress(cc[i]);
            }
            msg.setRecipients(Message.RecipientType.CC, address);
        }

        if (StringUtils.isNotBlank(bean.getMailBcc())) {
            String[] bcc = bean.getMailBcc().split(",");
            InternetAddress[] address = new InternetAddress[bcc.length];
            for (int i = 0; i < bcc.length; i++) {
                address[i] = new InternetAddress();
                address[i].setAddress(bcc[i]);
            }
            msg.setRecipients(Message.RecipientType.BCC, address);
        }

        msg.setSubject(bean.getTitle());
        msg.setSentDate(new Date());
        if (StringUtils.isNotBlank(bean.getAttachments())) {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(bean.getContent());
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            String[] files = bean.getAttachments().split(",");
            for (String f : files) {
                File file = new File(f);
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(file);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(file.getName());
                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        } else {
            msg.setDataHandler(new DataHandler(bean.getContent(), "text/plain"));
        }
        
        System.out.println("sending in process..");
        Transport transport = _session.getTransport("smtp");
        System.out.println("transport smtp ...");
        transport.connect(host, from, pass);
        System.out.println("connected ...");
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        System.out.println("sending in complete..");
    }

}
